package com.smasher.domain.holder

import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.smasher.domain.R
import com.smasher.domain.entity.BeanDomain
import com.smasher.widget.base.BaseRecyclerViewHolder

class DomainViewHolder(itemView: View) : BaseRecyclerViewHolder<BeanDomain?>(itemView) {

    private val domain: AppCompatTextView = itemView.findViewById(R.id.domain)
    private val state: AppCompatImageView = itemView.findViewById(R.id.state)
    private val container: ConstraintLayout = itemView.findViewById(R.id.container)

    private val normalColor: Int = ContextCompat.getColor(itemView.context, R.color.color_3B3F47)
    private val addColor: Int = ContextCompat.getColor(itemView.context, R.color.color_FF159EEC)

    override fun bindView() {
        super.bindView()
        val id = mItem?.id ?: -1
        domain.setTextColor(if (id > 0) normalColor else addColor)
        domain.text = buildDomain()
        domain.isSelected = isSelected
        state.visibility = if (isSelected) View.VISIBLE else View.INVISIBLE
        container.isSelected = isSelected
        container.setOnLongClickListener { v ->
            mOnItemClickListener?.onLongClick(v, mIndex)
            true
        }
    }

    private val isSelected: Boolean
        get() = mItem?.select ?: false

    private fun buildDomain(): String {
        val builder = StringBuilder()
        val id = mItem?.id ?: -1
        if (id == -1) {
            builder.append("点击新增")
        } else {
            builder.append(mItem?.scheme ?: "")
            builder.append("://")
            builder.append(mItem?.host ?: "")
            val portTemp = mItem?.port ?: -1
            if (portTemp > 0) {
                builder.append(":")
                builder.append(portTemp)
            }
            builder.append("/")
        }
        return builder.toString()
    }
}